import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import dayjs from 'dayjs'
import { saveToStorage, getFromStorage, STORAGE_KEYS } from '../utils/storage'

// 更新存储键名
if (!STORAGE_KEYS.MIND_ARCHIVES) {
  STORAGE_KEYS.MIND_ARCHIVES = 'time_capsule_mind_archives'
}

export const useMindArchiveStore = defineStore('mindArchive', () => {
  // 从本地存储加载思维存档数据
  const savedData = getFromStorage(STORAGE_KEYS.MIND_ARCHIVES, { archives: [] })
  
  // 存储所有思维存档
  const archives = ref(savedData.archives || [])
  
  // 创建新的思维存档
  function createArchive(data) {
    const id = Date.now().toString()
    const newArchive = {
      id,
      title: data.title,
      description: data.description,
      tags: data.tags || [],
      containerId: data.containerId, // 关联的预备容器ID（可选）
      blockingPoint: data.blockingPoint || '', // 卡点描述
      archiveTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      notes: data.notes || [], // 存档备注列表
      status: 'active' // active, restored
    }
    
    archives.value.push(newArchive)
    return id
  }
  
  // 添加存档备注
  function addArchiveNote(archiveId, note) {
    const archive = archives.value.find(a => a.id === archiveId)
    if (archive) {
      if (!archive.notes) {
        archive.notes = []
      }
      
      archive.notes.push({
        id: Date.now().toString(),
        content: note,
        createTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
      })
    }
  }
  
  // 恢复思维存档
  function restoreArchive(archiveId, restorationNote) {
    const archive = archives.value.find(a => a.id === archiveId)
    if (archive) {
      archive.status = 'restored'
      archive.restorationTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
      archive.restorationNote = restorationNote || ''
    }
  }
  
  // 获取所有思维存档
  const allArchives = computed(() => archives.value)
  
  // 获取活动状态的存档
  const activeArchives = computed(() => {
    return archives.value.filter(archive => archive.status === 'active')
  })
  
  // 获取已恢复的存档
  const restoredArchives = computed(() => {
    return archives.value.filter(archive => archive.status === 'restored')
  })
  
  // 按标签搜索存档
  function searchArchivesByTags(tags) {
    if (!tags || tags.length === 0) return archives.value
    
    return archives.value.filter(archive => {
      return tags.some(tag => archive.tags.includes(tag))
    })
  }
  
  // 按关键词搜索存档
  function searchArchivesByKeyword(keyword) {
    if (!keyword) return archives.value
    
    const lowerKeyword = keyword.toLowerCase()
    return archives.value.filter(archive => {
      return (
        archive.title.toLowerCase().includes(lowerKeyword) ||
        archive.description.toLowerCase().includes(lowerKeyword) ||
        archive.blockingPoint.toLowerCase().includes(lowerKeyword) ||
        archive.notes.some(note => note.content.toLowerCase().includes(lowerKeyword))
      )
    })
  }
  
  // 按日期范围搜索存档
  function searchArchivesByDateRange(startDate, endDate) {
    if (!startDate || !endDate) return archives.value
    
    return archives.value.filter(archive => {
      const archiveDate = dayjs(archive.archiveTime)
      return archiveDate.isAfter(startDate) && archiveDate.isBefore(endDate)
    })
  }
  
  // 监听数据变化，保存到本地存储
  watch(
    archives,
    () => {
      saveToAPI(STORAGE_KEYS.MIND_ARCHIVES, {
        archives: archives.value
      })
    },
    { deep: true }
  )
  
  return {
    archives,
    allArchives,
    activeArchives,
    restoredArchives,
    createArchive,
    addArchiveNote,
    restoreArchive,
    searchArchivesByTags,
    searchArchivesByKeyword,
    searchArchivesByDateRange
  }
})